/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.Sl;
import com.jeeplus.modules.ap.service.SlService;
import com.jeeplus.modules.fee.entity.*;
import com.jeeplus.modules.fee.service.FeeZzslService;
import com.jeeplus.modules.fee.service.NewReService;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.service.GoodsService;
import com.jeeplus.modules.infor.service.NewCustomersService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.*;
import com.jeeplus.modules.tms.service.NewBillService;
import com.jeeplus.modules.tms.service.NewTransportService;
import com.jeeplus.modules.wms.util.CopyUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tms.service.NewPlanningService;

/**
 * 委托单Controller
 * @author 李超辉
 * @version 2019-04-24
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/newPlanning")
public class NewPlanningController extends BaseController {

	@Autowired
	private NewPlanningService newPlanningService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private NewCustomersService newCustomersService;
	@Autowired
	private NewTransportService newTransportService;
	@Autowired
	private FeeZzslService zzslService;
	@Autowired
	private NewReService reService;
	@Autowired
	private NewBillService newBillService;
	@Autowired
	private SlService slService;
	@ModelAttribute
	public NewPlanning get(@RequestParam(required=false) String id) {
		NewPlanning entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = newPlanningService.get(id);
		}
		if (entity == null){
			entity = new NewPlanning();
		}
		return entity;
	}
	
	/**
	 * 委托单列表页面
	 */
	@RequiresPermissions("tms:newPlanning:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/tms/newPlanningList";
	}
	
		/**
	 * 委托单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:newPlanning:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(NewPlanning newPlanning, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		String s=request.getParameter("status");
		if(!pro.equals("总部")){
			newPlanning.setPro(pro);
		}
		Page<NewPlanning> page = newPlanningService.findPage(new Page<NewPlanning>(request, response), newPlanning);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑委托单表单页面
	 */
	@RequiresPermissions(value={"tms:newPlanning:view","tms:newPlanning:add","tms:newPlanning:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(NewPlanning newPlanning, Model model) {
		if(newPlanning.getIsNewRecord()){
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){
				newPlanning.setPro(pro);
			}
			newPlanning.setRemarks(UserUtils.getbsc());
			newPlanning.setDate(new Date());
			newPlanning.setStatus("已创建");
			newPlanning.setJf("不满足");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			NewPlanning p=new NewPlanning();
			p.setWtdh(code);
			List<NewPlanning> l=newPlanningService.findList(p);
			if(l==null||l.size()<1){
				newPlanning.setWtdh(code+"001"+"YS");
			}else{
				if(l.size()/10==0){
					newPlanning.setWtdh(code+"00"+(l.size()+1)+"YS");
				}else
				if(l.size()/100==0){
					newPlanning.setWtdh(code+"0"+(l.size()+1)+"YS");
				}else{newPlanning.setWtdh(code+(l.size()+1)+"YS");}

			}

		}

		model.addAttribute("newPlanning", newPlanning);
		return "modules/tms/newPlanningForm";
	}

	/**
	 * 保存委托单
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:newPlanning:add","tms:newPlanning:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(NewPlanning newPlanning, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, newPlanning)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		NumberFormat nf = NumberFormat.getInstance();
		Goods g=goodsService.get(newPlanning.getName().getId());
		newPlanning.setCode(g.getCode());
		newPlanning.setLx(g.getType().getName());
		newPlanning.setGg(g.getSpecifications());
		newPlanning.setUnit(g.getPacking());
		String weight=g.getGrossWeight();
		String volm=g.getVolume();
		double w=Double.parseDouble(weight)*Double.parseDouble(newPlanning.getGross());
		double v=Double.parseDouble(volm)*Double.parseDouble(newPlanning.getGross());
		newPlanning.setWeight(nf.format(w).replaceAll(",",""));
		newPlanning.setVoulm(nf.format(v).replaceAll(",",""));
		NewCustomers n = newCustomersService.get(newPlanning.getCustomer());
		List<PriceCustomers> li = n.getPriceCustomersList();
		//boolean bo = false;
		String  pc = null;
		for (PriceCustomers pp : li) {
			if (pp.getWidth().getWidth().equals(newPlanning.getWidth()) && pp.getZylx().equals(newPlanning.getZylx())) {
				pc = pp.getJsjg();
			//	bo = true;
			}
		}
//		if (!bo) {
//			j.setMsg("请先维护运价");
//			j.setSuccess(false);
//			return j;
//		}
		newPlanning.setPrice(pc);
		newPlanningService.save(newPlanning);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存委托单成功");
		return j;
	}
	
	/**
	 * 删除委托单
	 */
	@ResponseBody
	@RequiresPermissions("tms:newPlanning:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(NewPlanning newPlanning, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		newPlanningService.delete(newPlanning);
		j.setMsg("删除委托单成功");
		return j;
	}
	
	/**
	 * 批量删除委托单
	 */
	@ResponseBody
	@RequiresPermissions("tms:newPlanning:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			newPlanningService.delete(newPlanningService.get(id));
		}
		j.setMsg("删除委托单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tms:newPlanning:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(NewPlanning newPlanning, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "委托单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<NewPlanning> page = newPlanningService.findPage(new Page<NewPlanning>(request, response, -1), newPlanning);
    		new ExportExcel("委托单", NewPlanning.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出委托单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
	/**
	 * 生成计划
	 */
	@ResponseBody
	@RequestMapping(value = "scjh")
	public AjaxJson scjh(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			NewPlanning p=newPlanningService.get(id);
//			if(p.getPrice()==null||p.getPrice().equals("")){
//				j.setSuccess(false);
//				j.setMsg("请选择已维护运价的单子");
//				return j;
//			}
			if(p.getStatus().equals("已创建")){
				NewTransport planning=new NewTransport();
				planning= (NewTransport) CopyUtil.Copy(planning,p,false);
				planning.setJhstatus("未计划");
				planning.setPlanning(id);
				planning.setPcl("0");
				planning.setWf(p.getWeight());
				planning.setYf("0");
				planning.setWftj(p.getVoulm());
				newTransportService.save(planning);
				p.setStatus("已生成计划");
				newPlanningService.save(p);}
		}
		j.setMsg("生成计划成功");
		return j;
	}

	/**
	 * 取消计划
	 */
	@ResponseBody
	@RequestMapping(value = "qxjh")
	public AjaxJson qxjh(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		int i=0;
		int m=0;
		for(String id : idArray){
			m++;
			NewPlanning p=newPlanningService.get(id);
			NewTransport planning=newTransportService.findUniqueByProperty("planning",id);
			if(planning.getStatus().equals("已配载")){
				i++;
			}else{
            newTransportService.delete(planning);
            p.setStatus("已创建");
            newPlanningService.save(p);
			}

		}
        String msg="取消计划成功";
        if(i>0){
        	msg="共选择"+m+"条数据,"+i+"条计划已经操作取消失败！";
		}
		j.setMsg(msg);
		return j;
	}
	/**
	 * 批量计费
	 */
	@ResponseBody
	@Transactional(readOnly = false)
	@RequestMapping(value = "jf")
	public AjaxJson jf(String ids, RedirectAttributes redirectAttributes)throws Exception {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		boolean bol=true;
		for(String id : idArray) {
			NewPlanning p = newPlanningService.get(id);
			p.setStatus("已计费");
			String ii = p.getJsd().getId();
			if (ii.length() < 1) {
				j.setMsg("该地址没有维护结算地");
				j.setSuccess(false);
				return j;
			}
			NumberFormat nf = NumberFormat.getInstance();
			//创建应收
			NewRe r = new NewRe();
			r.setPid(id);
			r.setProject(p.getPro());
			r.setEntrustNumber(p.getWtdh());
			r.setShipmentNumbers(p.getZydh());
			r.setMileage(p.getHtlc());
			r.setBsc(UserUtils.getbsc());
			NewCustomers n = newCustomersService.get(p.getCustomer());
			List<PriceCustomers> li = n.getPriceCustomersList();
			boolean bo = false;
			PriceCustomers pc = null;
			for (PriceCustomers pp : li) {
				if (pp.getWidth().getWidth().equals(p.getWidth()) && pp.getZylx().equals(p.getZylx())) {
					pc = pp;
					bo = true;
				}
			}
			if (!bo) {
				j.setMsg("请先维护运价");
				j.setSuccess(false);
				return j;
			}
			String dj = pc.getJsjg();
			String fj = pc.getFjf();
			double pri = Double.parseDouble(dj);
			double ppp = Double.parseDouble(fj);
			Goods g = goodsService.get(p.getName().getId());
			Double wei = Double.parseDouble(p.getWeight().replaceAll(",", ""));
			Double vo = Double.parseDouble(p.getVoulm().replaceAll(",", ""));
			String o = g.getMoney();
			if (o == "" || o == null) {
				o = "0";
			}
			Double xs = Double.parseDouble(o);
			double pr = pri * wei * xs;
			r.setPrice(pri + "");
			r.setStatus("1");
			r.setSurplus(nf.format(pr).replaceAll(",", ""));
			r.setThdh(p.getThdh());
			r.setReceived("0");
			FeeZzsl f = new FeeZzsl();
			f.setPro(p.getPro());
			String sll = zzslService.findList(f).get(0).getSl();
			r.setSl(sll);
			Double hs = pr * (1 + Double.parseDouble(sll));
			r.setHs(nf.format(hs).replaceAll(",", ""));
			r.setFreight(nf.format(hs).replaceAll(",", ""));
			r.setWeight(p.getWeight());
			r.setArrive(p.getJsd().getName());
			r.setCompany(p.getShdw());
			r.setStart(p.getQyd().getName());
			r.setDate(p.getDate());
			r.setWidth(p.getWidth());
			r.setSite(p.getSite());
			r.setRemarks(p.getDzs());
			r.setAd("0");

			NewBill nb=new NewBill();
			nb.setPlanning(p.getId());
			nb.setPro(p.getPro());
			List<NewBill> bills=newBillService.findList(nb);
			double zyf=0.0;
			double xsyf=0.0;
			double kpyf=0.0;
			double xxyfxj=0.0;
			double xxyfyk=0.0;
			for(NewBill bill:bills){
               zyf+=Double.parseDouble(bill.getZyf());
               if(bill.getFktype().equals("线上")){
				   xsyf+=Double.parseDouble(bill.getZyf());
			   }else if(bill.getFktype().equals("开票")){
				   kpyf+=Double.parseDouble(bill.getZyf());
			   }else{
				   xxyfxj+=Double.parseDouble(bill.getZxj());
				 xxyfyk+=Double.parseDouble(bill.getZyk());

			   }
			}
			r.setZyf(nf.format(zyf).replaceAll(",",""));
			r.setXsyf(nf.format(xsyf).replaceAll(",",""));
			r.setKpyf(nf.format(kpyf).replaceAll(",",""));
			r.setXxyfxj(nf.format(xxyfxj).replaceAll(",",""));
			r.setXxyfyk(nf.format(xxyfyk).replaceAll(",",""));
			reService.save(r);
			newPlanningService.save(p);
		}

			j.setMsg("计费成功");
			return j;
	}
	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("tms:newPlanning:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<NewPlanning> list = ei.getDataList(NewPlanning.class);
			for (NewPlanning newPlanning : list){
				try{
					NumberFormat nf = NumberFormat.getInstance();
					Goods g=new Goods();
					g.setCode(newPlanning.getCode());
					g.setProject(newPlanning.getPro());
					List<Goods>l1=goodsService.findList(g);
					if(l1==null||l1.size()<1){
						failureNum++;
						continue;
					}
					g=l1.get(0);
					newPlanning.setName(g);
					newPlanning.setStatus("已创建");
					newPlanning.setJf("不满足");
					newPlanning.setCode(g.getCode());
					newPlanning.setLx(g.getType().getName());
					newPlanning.setGg(g.getSpecifications());
					newPlanning.setUnit(g.getPacking());
					String weight=g.getGrossWeight();
					String volm=g.getVolume();
					double w=Double.parseDouble(weight)*Double.parseDouble(newPlanning.getGross());
					double v=Double.parseDouble(volm)*Double.parseDouble(newPlanning.getGross());
					newPlanning.setWeight(nf.format(w).replaceAll(",",""));
					newPlanning.setVoulm(nf.format(v).replaceAll(",",""));
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
					String code=UserUtils.getUserAre()+sdf.format(new Date());
					NewPlanning p=new NewPlanning();
					p.setWtdh(code);
					List<NewPlanning> l=newPlanningService.findList(p);
					if(l==null||l.size()<1){
						newPlanning.setWtdh(code+"001"+"YS");
					}else{
						if(l.size()/10==0){
							newPlanning.setWtdh(code+"00"+(l.size()+1)+"YS");
						}else
						if(l.size()/100==0){
							newPlanning.setWtdh(code+"0"+(l.size()+1)+"YS");
						}else{newPlanning.setWtdh(code+(l.size()+1)+"YS");}

					}
					NewCustomers ne=new NewCustomers();
					ne.setPro(newPlanning.getPro());
					ne.setSite(newPlanning.getSite());
					ne.setQyd(newPlanning.getQyd());
					List<NewCustomers> li=newCustomersService.findList(ne);
					if(li==null||li.size()<1){
						failureNum++;
						continue;
					}
					ne=li.get(0);
					newPlanning.setCustomer(ne.getId());
					newPlanning.setDzs(ne.getDzs());
					newPlanning.setDzdcs(ne.getDzcs());
					newPlanning.setQyd(ne.getQyd());
					newPlanning.setJsd(ne.getJsd());
					newPlanning.setYsxl(ne.getYsxl());
					newPlanning.setHtlc(ne.getHtlc());
					newPlanning.setKhtstq(ne.getTsxq());
					newPlanning.setQrr(ne.getQrr());
					newPlanning.setQrrdh(ne.getQrrdh());
					newPlanning.setShdw(ne.getDwmc());
                    if(newPlanning.getDate()==null){
                    	newPlanning.setDate(new Date());
					}
					if(newPlanning.getType()==null||newPlanning.getType()==""){
						newPlanning.setType("销售订单");
					}
					if(newPlanning.getYsfs()==null||newPlanning.getYsfs()==""){
						newPlanning.setYsfs("汽运");
					}
					if(newPlanning.getJsfs()==null||newPlanning.getJsfs()==""){
						newPlanning.setJsfs("月结");
					}
					if(newPlanning.getJslx()==null||newPlanning.getJslx()==""){
						newPlanning.setJslx("现金");
					}
					if(newPlanning.getZylx()==null||newPlanning.getZylx()==""){
						newPlanning.setZylx("常规");
					}
					NewCustomers n = newCustomersService.get(newPlanning.getCustomer());
					List<PriceCustomers> li1 = n.getPriceCustomersList();
					boolean bo = false;
					String  pc = null;
					for (PriceCustomers pp : li1) {
						if (pp.getWidth().getWidth().equals(newPlanning.getWidth()) && pp.getZylx().equals(newPlanning.getZylx())) {
							pc = pp.getJsjg();
						}
					}
					newPlanning.setPrice(pc);
					newPlanningService.save(newPlanning);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					System.out.print(ex.getMessage());
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条委托单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条委托单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入委托单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/newPlanning/?repage";
    }
	
	/**
	 * 下载导入委托单数据模板
	 */
	@RequiresPermissions("tms:newPlanning:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "委托单数据导入模板.xlsx";
    		List<NewPlanning> list = Lists.newArrayList(); 
    		new ExportExcel("委托单数据", NewPlanning.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/newPlanning/?repage";
    }

}